package tech.aistar.util;

import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.InputStream;

/**
 * @author success
 * @version 1.0
 * @description:本类用来演示:
 * @date 2019/8/21 0021
 */
public class MybatisUtil {
    private static SqlSessionFactory sqlSessionFactory = null;

    //通过静态代码块来加载mybatis-config.xml文件
    static{
        //如果此处不进行异常的处理,那么静态代码块中的异常将会抛给JVM
        //选中代码 - ctrl+alt+t
        try {
            InputStream in = Thread.currentThread().getContextClassLoader().getResourceAsStream("mybatis-config.xml");
            sqlSessionFactory = new SqlSessionFactoryBuilder().build(in);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 获取SqlSession - 线程非安全的对象 - 负责进行CRUD操作
     * @return
     */
    public static SqlSession getSqlSession(){
        return sqlSessionFactory.openSession();
    }

    public static void close(SqlSession sqlSession){
        if(null!=sqlSession){
            sqlSession.close();
        }
    }
}
